#include <iostream>
#include <string>
#include <Magick++.h>

#include "../common/tools.h"

#include "separation.h"

using std::cout;
using std::endl;
using std::string;

using namespace Magick;

const int GridWidth = 256;
const int GridHeight = 256;

const int MaxIteration = 20000;
const int DumpInterval = 50;

SeparationCA ca(GridWidth, GridHeight);

void dumpCA(int iterNum)
{
  int width = ca.getWidth(), height = ca.getHeight();
  
  Image img;
  img.size( Geometry(width, height) );
  img.modifyImage();
  PixelPacket *pixel_cache = img.getPixels(0, 0, width, height);
  for (int y = 0; y != height; ++y)
  {
    for (int x = 0; x != width; ++x)
    {
      PixelPacket & p = *(pixel_cache + y * width + x);
      char cell = ca.getCell(x, y);
      p = ColorRGB(cell, cell, cell);
    }
  }

  string iterStr = format("{0}") % iterNum;
  string zeros = string(4 - iterStr.length(), '0');
  iterStr = zeros.append(iterStr);
  img.write( format("dump_{0}.png") % iterStr );
}



int main()
{
  srand(5);
  for (int y = 0; y < GridHeight; ++y)
    for (int x = 0; x < GridWidth; ++x)
      ca.setCell(x, y, (rand() < RAND_MAX / 2) ? 0 : 1);

  int dumpCount = 0;
  do {
    ca.iterate();

    if ( ca.getIteration() % DumpInterval == 0)
    {
      cout << "saving iteration " << ca.getIteration() << " ... ";
      dumpCA(++dumpCount);
      cout << "ok" << endl;
    }
  } while ( ca.getIteration() != MaxIteration );


  return 0;
}